import React, {useState} from 'react'
import { Layout, Menu, Dropdown, Avatar } from 'antd';
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
} from '@ant-design/icons';
import { 
  UserOutlined  
} from '@ant-design/icons';
import { withRouter } from 'react-router-dom';
import {store} from '../../store';
import {connect} from 'react-redux'

const { Header } = Layout;


function TopHeader(props) {
  console.log(props, 'header')
  const [collapsed, setCollapsed] = useState(false)
  const changeCollapsed = function() {
    setCollapsed(!collapsed)
    console.log(props)
    // let action = {
    //   type: 'collapsedFlag',
    //   value: !collapsed
    // }
    // store.dispatch(action)
    props.changeCollapsed()
  }
  const {role: {roleName}, userName} = JSON.parse(localStorage.getItem('token'))
  const menu = (
    <Menu>
      <Menu.Item>{roleName}</Menu.Item>
      <Menu.Item danger onClick={() => quit()}>退出</Menu.Item>
    </Menu>
  );
  const quit = () => {
    localStorage.removeItem('token')
    props.history.replace('/login')
  }

  return (
    <Header className="site-layout-background" style={{ padding: '0 16px' }}>
      {
        props.collapsedFlag ? 
        <MenuUnfoldOutlined onClick={changeCollapsed} /> : <MenuFoldOutlined onClick={changeCollapsed} />
      }
      <div style={{float: 'right'}}>
        <span>欢迎回来{userName}</span>
        <Dropdown overlay={menu}>
          <Avatar size="large" icon={<UserOutlined />} />
        </Dropdown>
      </div>
    </Header>
  )
}

const mapStateToProps = ({DataReducer: {collapsedFlag}}) => {
  // console.log(store, 99999)
  return {
    collapsedFlag
  }
}

// 作用: 将dispatch映射成props,通过父组件进行dispatch
const mapDispatchToPRops = {
  changeCollapsed() {
    return {
      type: 'collapsedFlag'
    }
  }
}

export default connect(mapStateToProps, mapDispatchToPRops )(withRouter(TopHeader))